﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AiXiu.Model;
using AiXiu.IDAL;
using System.Data.SqlClient;
using AiXiu.Common;

namespace AiXiu.DAL
{
    /// <summary>
    /// 登录注册表操作类
    /// </summary>
    public class LoginAndRegisterDAL : ILoginAndRegisterDAL
    {
        AiXiuDbContext db = new AiXiuDbContext();
        public TBLogins getLoginByUserName(string UserName)
        {
            return db.TBLogins.FirstOrDefault(t => t.UserName.Equals(UserName));
        }

        public int? register(TBLogins reg)
        {
            using (var transaction = db.Database.BeginTransaction())
            {
                try
                {
                    db.TBLogins.Add(reg);
                    int count1 = db.SaveChanges();


                    int id = getLoginByUserName(reg.UserName).Id;
                    db.TBUsers.Add(new TBUsers { Id = id, CreationTime = GetSqlMethod.getMsServerDateTime() });
                    int count2 = db.SaveChanges();

                    if (count1 + count2 >= 2)
                    {
                        transaction.Commit();
                        return id;
                    }
                    else
                    {
                        transaction.Rollback();
                        return null;
                    }
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw ex;
                }
            }
        }

        public TBLogins getLoginByMobileNumber(string mobileNumber)
        {
            return db.TBLogins.FirstOrDefault(t => t.MobileNumber.Equals(mobileNumber));
        }

        public TBLogins getLoginById(int id)
        {
            return db.TBLogins.FirstOrDefault(t => t.Id == id);
        }
    }
}
